package com.quan.weixin.rpc.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.quan.common.core.support.BaseService;
import com.quan.weixin.rpc.api.WeixinMenuService;
import com.quan.weixin.rpc.dao.mapper.WeixinMenuMapper;
import com.quan.weixin.rpc.model.WeixinMenu;

@Service
public class WeixinMenuServiceImpl extends BaseService<WeixinMenu> implements WeixinMenuService {
	
	@Autowired
	private WeixinMenuMapper mapper ;
	
	@Override
	public int deleteById(Object id) {
		return recursiveDelete(id);
	}
	
	private int recursiveDelete(Object id) {
		List<WeixinMenu> loadChildrenNode = this.selectChildren(Integer.valueOf(id.toString()), null) ;
		if(null != loadChildrenNode) {
			for (WeixinMenu channel : loadChildrenNode) {
				recursiveDelete(channel.getId());
			}
		}
		return super.deleteById(id) ;
	}

	@Override
	public List<WeixinMenu> selectRoot(String orders) {
		return this.mapper.selectRoot(orders);
	}

	@Override
	public List<WeixinMenu> selectChildren(Integer pid, String orders) {
		return this.mapper.selectChildren(pid, orders);
	}

	@Override
	public List<WeixinMenu> tree(WeixinMenu entity, String orderby) {
		List<WeixinMenu> list = new ArrayList<WeixinMenu>() ;
		
		List<WeixinMenu> selectRoot = this.selectRoot(orderby) ;
		for (WeixinMenu channel : selectRoot) {
			list.add(recursive(channel, orderby)) ;
		}
		return list;
	}
	
	private WeixinMenu recursive(WeixinMenu menu, String orderby) {
		List<WeixinMenu> selectChildren = this.selectChildren(menu.getId(), orderby) ;
		if(null != selectChildren && !selectChildren.isEmpty()) {
			List<WeixinMenu> children = new ArrayList<WeixinMenu>() ;
			
			for (WeixinMenu childChannel : selectChildren) {
				children.add(recursive(childChannel, orderby)) ;
			}
			
			menu.setChildren(children);
		}
		return menu ;
	}

	@Override
	public List<Integer> getParents(Integer id) {
		List<Integer> pidList = new ArrayList<Integer>() ;
		
		WeixinMenu channel = super.selectOneById(id) ;
		if(null != channel) {
			if(null != channel.getPid() && channel.getPid() > 0) {
				getParent(pidList, channel) ;
			} else {
				//pidList.add(channel.getId()) ;
			}
		}
		return pidList;
	}
	
	private void getParent(List<Integer> pidList, WeixinMenu channel) {
		pidList.add(channel.getId()) ;
		
		if(null != channel) {
			if(null != channel.getPid() && channel.getPid() > 0) {
				WeixinMenu channelParent = super.selectOneById(channel.getPid()) ;
				getParent(pidList, channelParent) ;
			}
		}
	}

	@Override
	public WeixinMenu selectMenyByKey(String eventKey) {
		return this.mapper.selectMenyByKey(eventKey);
	}
	
}
